import ReactDOM from 'react-dom';
import { observable, action, toJS } from 'mobx';
import { Modal } from 'antd';
import { WeaLocaleProvider, WeaTools } from 'ecCom';
import * as _ from 'lodash';
import * as LOGIN_API from '../apis/login';
import * as THEME_API from '../apis/theme';
import { doEvent } from '../util/eventUtil';
import { setLSValue, initLSValue } from '../util/loginUtil';
import { jsAsyncLoad, cssAsyncLoad, formatMenuData, setE9ThemeStyle, setFontSize } from '../util/themeUtil';

const getLabel = WeaLocaleProvider.getLabel;

export default class ThemeStore {
  // 主题加载状态
  @observable loading = true;
  // 插件加载状态
  @observable pluginloading = true;
  // 自定义主题组件加载状态
  @observable customloading = false;
  // 地址栏查询参数
  @observable searchParams = {};
  // 插件相关
  @observable pluginIds = [];
  @observable pluginInsertCount = 0;
  @observable pluginReload = false;
  // 多语言
  @observable multiLangs = [];
  @observable langId = '';
  // 主题信息
  @observable themeInfo = {};
  // 前端菜单
  @observable frontEndMenu = [];
  // 顶部菜单
  @observable topMenuObj = {
    topMenu: [],
    topMenuSelected: {},
  };
  @observable topMenuVisible = false;
  // 左侧菜单
  @observable leftMenuObj = {
    leftMenu: [],
    leftMenuSelected: {},
    leftMenuType: 'portal', // portal | email
  };
  @observable leftMenuMode = 'vertical'; // inline | vertical
  // 选中菜单
  @observable selectedMenuIds = '';
  @observable selectedMenuKeys = [];
  // 我的门户
  @observable hiddenMyPortal = true;
  // 常用菜单
  @observable showFreqUseMenu = false;
  @observable freqUseMenu = [];
  @observable freqUseMenuVisible = false;
  // 快捷搜索
  @observable showQuickSearch = false;
  @observable quickSearchTypes = [];
  @observable quickSearchTypesVisible = false;
  @observable quickSearchTypesSelected = {};
  @observable quickSearchMenus = []; // 快捷搜索栏搜索时前端菜单搜索推荐
  @observable quickSearchAssociate = []; // 快捷搜索栏搜索时微搜联想推荐
  @observable quickSearchRcmdVisible = false;
  @observable quickSearchShowRcmd = false; // 快捷搜索栏是否显示搜索推荐
  @observable quickSearchShowWs = false; // 快捷搜索栏是否显示微搜
  // 工具栏
  @observable toolbarMenu = [];
  @observable toolbarMoreMenu = [];
  @observable toolbarMoreMenuVisible = false;
  // 账号栏
  @observable account = {};
  @observable accountVisible = false;
  @observable accountSize = 1;
  @observable accountList = [];
  @observable accountListVisible = false;
  @observable accountMenu = [];
  @observable accountMoreMenu = [];
  @observable fontSettingVisible = false;
  @observable langSettingVisible = false;
  // 翻译模式权限
  @observable translatepower = false;
  @observable translatepage = 0;

  // 执行主题加载前事件
  @action
  doBeforThemeRenderEvent(callback) {
    doEvent('beforThemeRender', callback);
  }

  // 执行主题加载后事件
  @action
  doAfterThemeRenderEvent() {
    doEvent('afterThemeRender', () => {
      if (window.pluginDelayTime && parseInt(window.pluginDelayTime) > 0) {
        setTimeout(() => {
          this.getPlugins();
          this.pluginloading = false;
        }, parseInt(window.pluginDelayTime));
      } else {
        this.getPlugins();
        this.pluginloading = false;
      }
    });
  }

  @action
  setThemeInfo(themeInfo) {
    this.themeInfo = Object.assign({}, this.themeInfo, themeInfo);
  }

  @action
  getThemeInfo(params = {}) {
    this.searchParams = params; // 地址栏查询参数

    if (window.location.pathname == '/spa/theme/static/index.html') {
      params.from = 'static';
    }

    // 缓存清除
    const isInitLSValue = WeaTools.ls.getJSONObj('isInitLSValue');
    if (!isInitLSValue) {
      initLSValue();
    }

    // 自定义跳转
    const { gopage, target = '1' } = params;
    if (gopage) {
      if (target == '2') {
        window.open(gopage, '_blank');
      } else if (target == '3') {
        window.location.href = gopage;
        return;
      }
    }

    // 加载主题
    this.loading = true;
    this.doBeforThemeRenderEvent(() => {
      const themeInfo = WeaTools.ls.getJSONObj('theme-themeInfo');
      if (themeInfo && !params.from) {
        this.onLoadTheme(themeInfo);
        this.loading = false;
      }

      THEME_API.getMyTheme(params).then((result) => {
        const { data = {} } = result;
        let _themeInfo = data;
        const { themeType, themeData = {}, layoutData = {} } = _themeInfo;

        if (themeType == 'ecology9') {
          const { styleConfig = '{}' } = themeData;
          _themeInfo = {
            ...data,
            themeData: { ...themeData, styleConfig: JSON.parse(styleConfig.replace(/&quot;/g, '"')) },
          };
        } else if (themeType == 'ECustom') {
          const { layoutSetting = '{}' } = layoutData;
          _themeInfo = {
            ...data,
            layoutData: { ...layoutData, layoutSetting: JSON.parse(layoutSetting) },
          };
        }else if(themeType == 'ecology8'){
          _themeInfo.themeLayoutType  = '1'
          this.setThemeInfo(_themeInfo)
        }

        if (!_.isEqual(_themeInfo, themeInfo) || !!params.from) {
          this.onLoadTheme(_themeInfo, !params.from);
        }

        this.loading = false;
      });
    });
  }

  @action
  onLoadTheme(themeInfo, isCache = true) {
    this.themeInfo = themeInfo;
    isCache && WeaTools.ls.set('theme-themeInfo', themeInfo);

    const { themeTitle, themeType, themeLayoutType, themeFontSize, themeData = {}, layoutData = {} } = themeInfo;

    // 设置浏览器窗口标题
    document.title = themeTitle || '';

    // 设置字体大小
    setFontSize(themeFontSize || '12');

    if (themeType == 'ecology9') {
      if (themeLayoutType == '5') {
        setE9ThemeStyle(null);
      } else {
        const { styleConfig = {} } = themeData;
        setE9ThemeStyle(styleConfig);
      }
    } else if (themeType == 'ECustom') {
      this.onLoadECustomTheme(layoutData);
    }
  }

  @action
  onLoadECustomTheme(layoutData = {}) {
    const { layoutCustom, layoutConfig } = layoutData;

    if (layoutCustom == '1' && layoutConfig && layoutConfig.id) {
      WeaTools.loadDevModules(layoutConfig.id, layoutConfig.module).then(() => {
        const _interval = window.setInterval(() => {
          if (window[layoutConfig.module]) {
            this.customloading = true;
            window.clearInterval(_interval);
          }
        }, 100);
      });
    }
  }

  // 获取多语言
  @action
  getMultiLangs(params = {}) {
    LOGIN_API.getActiveLanguage(params).then((result) => {
      if (result.status == '1') {
        const { activeLanguageInfo, activeLanguageIds, languageIdentify } = result;
        this.multiLangs = activeLanguageInfo;
        setLSValue('login', 'multiLangs', activeLanguageInfo);
        WeaTools.ls.set('activeLanguageIds', activeLanguageIds);
        WeaTools.ls.set('languageIdentify', languageIdentify);
      }
    });
  }

  // 获取翻译模式权限
  @action
  getTranslatepower() {
    WeaTools.callApi('/api/system/language/base/isShowTransMode', 'GET').then((result) => {
      const { isShow } = result;
      this.translatepower = isShow;
    });
  }

  @action
  getTranslatepage() {
    this.translatepage = WeaTools.ls.getStr('ennableTrans') || 0;

    WeaTools.callApi('/api/system/language/base/getTransStat', 'GET').then((result) => {
      const { stat } = result;
      if (stat == true) {
        this.translatepage = 1;
        WeaTools.ls.set('ennableTrans', 1);
      } else {
        this.translatepage = 0;
        WeaTools.ls.set('ennableTrans', 0);
      }
    });
  }

  @action
  setTranslatepage(stat) {
    WeaTools.callApi('/api/system/language/base/changeTransStat', 'GET', { stat }).then((result) => {
      const { status } = result;
      if (status == '1') {
        this.translatepage = stat;
        initLSValue();
        WeaTools.ls.set('ennableTrans', stat);
        window.location.reload();
      }
    });
  }

  @action
  getFrontEndMenu() {
    THEME_API.getFrontEndMenu().then((result) => {
      const { data = [] } = result;
      const frontEndMenu = formatMenuData(data);
      this.frontEndMenu = frontEndMenu;
    });
  }

  @action
  getThemeConfig(params) {
    // 加载多语言
    this.getMultiLangs(params);

    // 加载翻译模式
    this.getTranslatepage();

    // 加载前端菜单
    this.getFrontEndMenu();

    // 左侧菜单展示模式
    const leftMenuMode = WeaTools.ls.getStr('theme-leftMenuMode');
    if (leftMenuMode) {
      // 有缓存，取缓存数据
      this.onLeftMenuModeChange(leftMenuMode);
    }

    THEME_API.getThemeConfig().then((result) => {
      const { data = {} } = result;
      const { openLeftMenu, hiddenMyPortal, showFreqUseMenu, showQuickSearch, quickSearchShowRcmd } = data;

      if (!leftMenuMode) {
        // 无缓存，取接口数据
        this.onLeftMenuModeChange(openLeftMenu == '1' ? 'inline' : 'vertical');
      }
      this.hiddenMyPortal = hiddenMyPortal == '1';
      this.showFreqUseMenu = showFreqUseMenu == '1';
      this.showQuickSearch = showQuickSearch == '1';
      this.quickSearchShowRcmd = quickSearchShowRcmd == '1';
    });
  }

  @action
  getPlugins() {
    jQuery('[id^=theme-plugin]').remove();

    window.generatePluginAreaHtml = (html, key) => {
      const element = document.getElementById(key);
      if (element) {
        element.innerHTML = html;
        this.pluginInsertCount++;
      }
    };

    window.generatePluginAreaCom = (com, key) => {
      const element = document.getElementById(key);
      if (element) {
        ReactDOM.render(com, element);
        this.pluginInsertCount++;
      }
    };

    setTimeout(() => {
      THEME_API.getPlugins().then((result) => {
        const { data = {} } = result;
        const { pluginIds = [], pluginCSS = [], pluginJS = [] } = data;

        const _pluginIds = _.uniq(pluginIds);
        _.pull(_pluginIds, 'docPop', 'hrm', 'checkPlugin', 'onlinePlugin', 'showHelp', 'showEmessage');

        this.pluginIds = _pluginIds;
        this.pluginReload = false;

        for (let i = 0, len = pluginCSS.length; i < len; i++) {
          cssAsyncLoad(pluginCSS[i], null);
        }
        for (let j = 0, len2 = pluginJS.length; j < len2; j++) {
          jsAsyncLoad(pluginJS[j], null);
        }
      });
    }, 100);
  }

  @action
  removePlugins() {
    jQuery('[id^=theme-plugin]').remove();
    jQuery('#theme-font').remove();
    jQuery('#IMbg', parent.document).remove();
    jQuery('#immsgdiv', parent.document).remove();
    jQuery('#addressdiv', parent.document).remove();
  }

  @action
  getTopMenu(pathname, query = {}, params = {}) {
    // 获取顶部和左侧选中的菜单
    let menuIds = [];
    if (query.menuIds) {
      menuIds = query.menuIds.split(',');
    }
    let topMenuId = menuIds[0];
    let leftMenuId = menuIds[1];

    // 加载顶部菜单
    let isLoaded = false;
    const topMenu = WeaTools.ls.getJSONObj('theme-topMenu');
    if (topMenu && topMenu.length) {
      isLoaded = true;

      const topMenuSelected = this.getTopMenuSelected(topMenu, topMenuId, pathname) || {};
      this.topMenuObj = { ...this.topMenuObj, topMenu, topMenuSelected };
      topMenuId = topMenuSelected.infoId || topMenuSelected.id;
      this.getLeftMenu(topMenuId, leftMenuId, pathname, query);
    }

    THEME_API.getTopMenu(params).then((result) => {
      const { data = [] } = result;
      WeaTools.ls.set('theme-topMenu', data);

      const topMenuSelected = this.getTopMenuSelected(data, topMenuId, pathname) || {};
      this.topMenuObj = { ...this.topMenuObj, topMenu: data, topMenuSelected };
      if (!isLoaded) {
        topMenuId = topMenuSelected.infoId || topMenuSelected.id;
        this.getLeftMenu(topMenuId, leftMenuId, pathname, query);
      }
    });
  }

  getLeftMenu(topMenuId, leftMenuId, pathname, query = {}) {
    let leftMenu = null;

    if (topMenuId == 0) {
      // 门户
      leftMenu = null;
    } else if (topMenuId == 536) {
      // 邮件
      leftMenu = null;
    } else {
      const frontEndMenu = this.frontEndMenu;
      if (frontEndMenu) {
        for (let i = 0, len = frontEndMenu.length; i < len; i++) {
          if (frontEndMenu[i].infoId == topMenuId) {
            leftMenu = frontEndMenu[i].child || [];
            break;
          }
        }
      }
    }

    if (leftMenu && leftMenu.length) {
      this.setLeftMenu(leftMenu, topMenuId, leftMenuId, pathname, query);
    } else {
      let leftMenuPromise = null;
      if (topMenuId == 0) {
        // 门户
        leftMenuPromise = THEME_API.getPortalMenu();
      } else if (topMenuId == 536) {
        // 邮件
        leftMenuPromise = THEME_API.getEmailMenu();
      } else {
        leftMenuPromise = THEME_API.getFrontEndMenu();
      }

      leftMenuPromise.then((result) => {
        if (topMenuId == 0) {
          // 门户
          const { data = {} } = result;
          const { defaulthpid, showlasthp, lasthpid, menuList = [] } = data;
          // 访问首页时，需要获取是否有启用默认门户或者记住最后一次访问的门户
          if (!leftMenuId && (!pathname || pathname == 'main' || pathname == '/main' || pathname == 'main/' || pathname == '/main/')) {
            leftMenuId = showlasthp == '1' && lasthpid && lasthpid != '0' ? lasthpid : defaulthpid && defaulthpid != '0' ? defaulthpid : null;
          }
          leftMenu = formatMenuData(menuList, '0');
        } else if (topMenuId == 536) {
          // 邮件
          const { themeLayoutType } = this.themeInfo;
          if (themeLayoutType == 1) {
            // 主题默认布局需要加载邮件菜单，顶部栏和侧边栏不需要加载邮件菜单
            leftMenu = formatMenuData(result, '536');
          }
        } else {
          const { data = [] } = result;
          const frontEndMenu = formatMenuData(data);
          this.frontEndMenu = frontEndMenu;
          for (let i = 0, len = frontEndMenu.length; i < len; i++) {
            const item = frontEndMenu[i];
            if (item.infoId == topMenuId) {
              leftMenu = item.child;
              break;
            }
          }
        }

        this.setLeftMenu(leftMenu, topMenuId, leftMenuId, pathname, query);
      });
    }
  }

  setLeftMenu(leftMenu, topMenuId, leftMenuId, pathname, query = {}) {
    if (leftMenu && leftMenu.length) {
      let leftMenuSelected = {};
      if (leftMenuId || (pathname && pathname != 'main' && pathname != '/main' && pathname != 'main/' && pathname != '/main/')) {
        leftMenuSelected = this.getLeftMenuSelected(leftMenu, leftMenuId, pathname) || {};
      } else if (topMenuId == 536) {
        // 邮件
        leftMenuSelected = leftMenu[2];
      } else {
        leftMenuSelected = leftMenu[0];
        // 获取左侧菜单中第一个有链接的菜单
        if (!leftMenuSelected || (!leftMenuSelected.mobxrouteurl && !leftMenuSelected.fullrouteurl && !leftMenuSelected.url)) {
          const loop = (data) => {
            let selected = null;
            for (let i = 0, len = data.length; i < len; i++) {
              const item = data[i];
              if ((item.url != '' && item.url != 'javascript:void(0)') || item.mobxrouteurl != '' || item.fullrouteurl != '') {
                selected = item;
                break;
              } else {
                selected = loop(item.child || []);
                if (selected) {
                  break;
                }
              }
            }
            return selected;
          };
          leftMenuSelected = loop(leftMenu) || {};
        }
      }

      let leftMenuType = 'portal';
      if (topMenuId == 536) {
        // 邮件
        leftMenuType = 'email';
      }

      const { gopage, target = '1' } = query;
      if (gopage && target == '1') {
        this.leftMenuObj = { ...this.leftMenuObj, leftMenu, leftMenuSelected: {}, leftMenuType };
        this.onLoadMain({ url: gopage, target: 'mainFrame' });
      } else {
        this.leftMenuObj = { ...this.leftMenuObj, leftMenu, leftMenuSelected, leftMenuType };
        this.onSelectedMenuKeysChange(`${topMenuId},${leftMenuSelected.infoId}`, [leftMenuSelected.id]);
        if (!pathname || pathname == 'main' || pathname == '/main' || pathname == 'main/' || pathname == '/main/') {
          this.onLoadMain(leftMenuSelected);
        }
      }
    } else {
      const { topMenuSelected = {} } = this.topMenuObj;
      const { parentId, infoId, id } = topMenuSelected;
      const leftMenuSelected = { id: `${parentId || '0'}-${infoId || id}`, infoId };
      this.leftMenuObj = { ...this.leftMenuObj, leftMenu: [], leftMenuSelected };
      this.onSelectedMenuKeysChange(`${topMenuId},${leftMenuSelected.infoId}`, [leftMenuSelected.id]);
      if (!pathname || pathname == 'main' || pathname == '/main' || pathname == 'main/' || pathname == '/main/') {
        this.onLoadMain(topMenuSelected);
      }
    }
  }

  getTopMenuSelected(topMenu, topMenuId, pathname) {
    let topMenuSelected = {};
    if (topMenu && topMenu.length) {
      topMenuSelected = topMenu[0];
    }

    let routes = [];
    if (pathname) {
      routes = pathname.split('/');
    }
    const module = routes[1];

    for (let i = 0, len = topMenu.length; i < len; i++) {
      const item = topMenu[i];
      if (topMenuId) {
        if (item.infoId == topMenuId) {
          topMenuSelected = item;
          break;
        }
      } else if (module && (item.routeurl == module || item.mobxrouteurl == module)) {
        topMenuSelected = item;
        break;
      }
    }

    return topMenuSelected;
  }

  getLeftMenuSelected(leftMenu, leftMenuId, pathname) {
    let leftMenuSelected = null;

    for (let i = 0, len = leftMenu.length; i < len; i++) {
      const item = leftMenu[i];
      if (leftMenuId) {
        if (item.infoId == leftMenuId) {
          leftMenuSelected = item;
          break;
        }
      } else if (item.mobxrouteurl && pathname.endsWith(item.mobxrouteurl)) {
        leftMenuSelected = item;
        break;
      }

      if (item.child && item.child.length) {
        leftMenuSelected = this.getLeftMenuSelected(item.child, leftMenuId, pathname);
        if (leftMenuSelected) {
          return leftMenuSelected;
        }
      }
    }

    return leftMenuSelected;
  }

  @action
  getHome() {
    const topMenuObj = this.topMenuObj;
    const { topMenu = [] } = topMenuObj;

    let topMenuSelected = {};
    if (topMenu && topMenu.length) {
      topMenuSelected = topMenu[0];
    }

    this.topMenuObj = { ...topMenuObj, topMenuSelected };
    const topMenuId = topMenuSelected.infoId || topMenuSelected.id;
    this.getLeftMenu(topMenuId, null, '/main');
  }

  @action
  onTopMenuVisibleChange(visible) {
    this.topMenuVisible = visible;
  }

  @action
  onTopMenuSelectedChange(topMenuSelected = {}, leftMenuId, pathname) {
    this.topMenuObj = { ...this.topMenuObj, topMenuSelected };
    const topMenuId = topMenuSelected.infoId || topMenuSelected.id;
    this.getLeftMenu(topMenuId, leftMenuId, pathname);
    this.setTopMenuStatictics(topMenuId);
  }

  @action
  setTopMenuStatictics(mid) {
    THEME_API.setTopMenuStatictics({ mid });
  }

  @action
  onLeftMenuModeChange(leftMenuMode) {
    this.leftMenuMode = leftMenuMode;
    WeaTools.ls.set('theme-leftMenuMode', leftMenuMode);

    const width = leftMenuMode == 'inline' ? '197px' : '61px';
    const aside = document.querySelector('.e9theme-layout-aside');
    const main = document.querySelector('.e9theme-layout-main');
    aside && (aside.style.width = width);
    main && (main.style.marginLeft = width);
  }

  @action
  onLeftMenuSelectedChange(leftMenuSelected = {}) {
    this.leftMenuObj = { ...this.leftMenuObj, leftMenuSelected };
    this.onSelectedMenuKeysChange(`${leftMenuSelected.topId},${leftMenuSelected.infoId}`, [leftMenuSelected.id]);
  }

  @action
  onSelectedMenuKeysChange(selectedMenuIds, selectedMenuKeys) {
    this.selectedMenuIds = selectedMenuIds;
    this.selectedMenuKeys = selectedMenuKeys;
  }

  @action
  getFreqUseMenu() {
    THEME_API.getFreqUseMenu().then((result) => {
      const data = result;
      this.freqUseMenu = data;
    });
  }

  @action
  onFreqUseMenuVisibleChange(visible) {
    this.freqUseMenuVisible = visible;
  }

  @action
  getQuickSearchTypes() {
    THEME_API.getQuickSearchTypes().then((result) => {
      const { data = [] } = result;
      if (data && data.length) {
        this.quickSearchTypes = data;
        this.quickSearchTypesSelected = data[0];
        data.forEach((item) => {
          if (item.type == '9') {
            this.quickSearchShowWs = true;
          }
        });
      }
    });
  }

  @action
  onQuickSearchTypesVisibleChange(visible) {
    this.quickSearchTypesVisible = visible;
  }

  @action
  onQuickSearchTypesSelectedChange(quickSearchTypesSelected) {
    this.quickSearchTypesSelected = quickSearchTypesSelected;
  }

  @action
  onQuickSearchRcmdVisibleChange(visible) {
    this.quickSearchRcmdVisible = visible;
  }

  @action
  setQuickSearchShowRcmd(quickSearchShowRcmd) {
    THEME_API.setQuickSearchShowRcmd({ quickSearchShowMenu: quickSearchShowRcmd }).then(() => {
      this.quickSearchShowRcmd = false;
    });
  }

  @action
  getToolbarMenu() {
    THEME_API.getToolbarMenu().then((result) => {
      const { data = [] } = result;
      this.toolbarMenu = data;
    });
  }

  @action
  getToolbarMoreMenu() {
    THEME_API.getToolbarMoreMenu().then((result) => {
      const { data = [] } = result;
      this.toolbarMoreMenu = data;
    });
  }

  @action
  onToolbarMoreMenuVisibleChange(visible) {
    this.toolbarMoreMenuVisible = visible;
  }

  @action
  getAccount() {
    THEME_API.getAccount().then((result) => {
      const { data = {} } = result;
      const langId = data.userLanguage || '7';
      this.langId = langId;
      this.account = data;
      this.getAccountList();
      WeaTools.ls.set('languageidweaver', langId);
      WeaTools.ls.set('theme-account', data);
    });
  }

  @action
  onAccountChange(userid) {
    WeaTools.ls.set('isInitLSValue', false);
    THEME_API.changeAccount({ shiftid: userid }).then((result) => {
      if (result.status == '1') {
        window.location.reload();
      }
    });
  }

  @action
  onAccountVisibleChange(visible) {
    if (window.accountVisible) {
      visible = true;
    }

    this.accountVisible = visible;
  }

  @action
  getAccountList(subcompanyid) {
    const { accountlist = [] } = this.account;

    if (subcompanyid) {
      this.accountList = accountlist.filter((item) => item.subcompanyid == subcompanyid);
      window.accountVisible = false;
      window.accountListVisible = false;
    } else {
      this.accountSize = accountlist.length;
      this.accountList = accountlist;
    }
  }

  @action
  onAccountListVisibleChange(visible) {
    if (window.accountListVisible) {
      visible = true;
    }

    this.accountListVisible = visible;
  }

  @action
  getAccountMenu() {
    THEME_API.getAccountMenu().then((result) => {
      const { data = [] } = result;
      this.accountMenu = data;
    });
  }

  @action
  getAccountMoreMenu() {
    THEME_API.getAccountMoreMenu().then((result) => {
      const { data = [] } = result;
      this.accountMoreMenu = data;
    });
  }

  @action
  onFontSettingVisibleChange(visible) {
    this.fontSettingVisible = visible;
  }

  @action
  onLangSettingVisibleChange(visible) {
    this.langSettingVisible = visible;
  }

  @action
  onQuickSearch(obj) {
    const { from, type, value } = obj;

    const _types = toJS(this.quickSearchTypes);
    let _selected = toJS(this.quickSearchTypesSelected);

    for (let i = 0, len = _types.length; i < len; i++) {
      if (_types[i].type == type) {
        _selected = _types[i];
        break;
      }
    }

    const _type = _selected.type;
    const _contentType = _selected.contentType;
    let _url = _selected.url + encodeURIComponent(value);

    if (from == 'theme') {
      THEME_API.getQuickSearchRoute({ type: _type, value }).then((result) => {
        this.onLoadMain({ url: result.route || _url });
      });
    } else if (from == 'fullSearch') {
      if (_url.indexOf('QuickSearchOperation.jsp') != -1) {
        _url += `&fromES=1&contentType=${_contentType}`;
      }
      this.onLoadMain({ url: _url });
    }
  }

  @action
  onRcmdSearch(value) {
    const frontEndMenu = this.frontEndMenu;
    const quickSearchMenus = [];

    const loop = (moduleId, moduleName, item) => {
      const child = item.child;
      if (child && child.length) {
        for (let i = 0, len = child.length; i < len; i++) {
          const { name = '', pinyin = '' } = child[i];
          if (name.toLowerCase().indexOf(value.toLowerCase()) != -1 || pinyin.indexOf(value.toLowerCase()) != -1) {
            child[i].moduleId = moduleId;
            child[i].moduleName = moduleName;
            quickSearchMenus.push(child[i]);
          }
          loop(moduleId, moduleName, child[i]);
        }
      }
    };

    frontEndMenu.forEach((item) => {
      const moduleId = item.infoId || '';
      const moduleName = item.name || '';

      const { name = '', pinyin = '' } = item;
      if (name.toLowerCase().indexOf(value.toLowerCase()) != -1 || pinyin.indexOf(value.toLowerCase()) != -1) {
        item.moduleId = moduleId;
        item.moduleName = moduleId;
      }
      loop(moduleId, moduleName, item);
    });

    this.quickSearchMenus = quickSearchMenus;

    if (this.quickSearchShowWs) {
      THEME_API.getWsAssociate({ key: value }).then((data) => {
        this.quickSearchAssociate = data.result || [];
      });
    }
  }

  @action
  onLoadEmailMenu() {
    THEME_API.getEmailMenu().then((result) => {
      const leftMenu = formatMenuData(result, '536');
      this.leftMenuObj = { ...this.leftMenuObj, leftMenu };
    });
  }

  @action
  onClearEmail(leftMenuSelected) {
    Modal.confirm({
      title: getLabel(15172, '系统提示'),
      content: getLabel(384163, '确定要清空该文件夹下的邮件吗？'),
      onOk: () => {
        WeaTools.callApi('/api/email/setting/operateUserMailFolder', 'POST', {
          operation: 'clear',
          folderId: '-4',
        }).then(() => {
          this.onLeftMenuSelectedChange(leftMenuSelected);
          this.onLoadMain(leftMenuSelected);
        });
      },
    });
  }

  @action
  onLoadLeftMenuCount() {
    let levelid = '';
    jQuery('span[id^="num_"]').each(function () {
      const id = jQuery(this).attr('id');
      if (!/portal/.test(id)) {
        // 非门户菜单
        if (levelid == '') {
          levelid = id.replace(/\D/g, '');
        } else {
          levelid = `${levelid},${id.replace(/\D/g, '')}`;
        }
      }
    });

    if (levelid) {
      WeaTools.callApi('/workflow/request/menuCount.jsp', 'POST', { levelid }).then((result) => {
        try {
          for (let key in result) {
            jQuery(`#${key}`).html(result[key]);
          }
        } catch (e) {}
      });
    }
  }

  @action
  onThemeChange(params, callback) {
    THEME_API.setMyTheme(params).then((result) => {
      const { data = {} } = result;
      const { themeType, themeData = {}, layoutData = {}, themeLayoutType } = data;
      const { styleConfig = '{}' } = themeData;
      const themeInfo = {
        ...data,
        themeData: { ...themeData, styleConfig: JSON.parse(styleConfig.replace(/&quot;/g, '"')) },
      };
      if(themeType == 'ecology8'){
        themeInfo.themeLayoutType  = '1'
        this.setThemeInfo(themeInfo)
      }
      this.pluginReload = true;
      this.onLoadTheme(themeInfo);
      const {leftMenuSelected} = this.leftMenuObj
      this.onLoadMain(leftMenuSelected);
      if (callback && typeof callback == 'function') {
        callback();
      }
      
    });
  }

  @action
  onThemeTsChange(params, callback) {
    THEME_API.setMyThemeTs(params).then((result) => {
      const { data = {} } = result;
      const { themeType, layoutData = {} } = data;
      if (themeType == 'ECustom') {
        const { layoutSetting = '{}' } = layoutData;
        data.layoutData = { ...layoutData, layoutSetting: JSON.parse(layoutSetting) };
      }
      this.onLoadTheme(result.data);
      if (callback && typeof callback == 'function') {
        callback();
      }
    });
  }

  @action
  onColorChange(params, callback) {
    THEME_API.setMyThemeColor(params).then(() => {
      const themeInfo = { ...this.themeInfo, themeData: { cssfile: params.color } };
      this.onLoadTheme(themeInfo);
      if (callback && typeof callback == 'function') {
        callback();
      }
    });
  }

  @action
  onLayoutChange(params, callback) {
    const { type } = params;
    THEME_API.setMyThemeLayout({ layout: type }).then(() => {
      const themeInfo = { ...this.themeInfo, themeLayoutType: type };
      if (type == '5') {
        themeInfo.themeType = 'ecology9';
        // themeInfo.themeData = {};
      }
      this.pluginReload = true;
      this.onLoadTheme(themeInfo);
      if (callback && typeof callback == 'function') {
        callback();
      }
    });
  }

  @action
  onFontSizeChange(fontSize) {
    setFontSize(fontSize);
    THEME_API.setMyFontSize({ fontSize }).then(() => {
      const themeInfo = { ...this.themeInfo, themeFontSize: fontSize };
      this.themeInfo = themeInfo;
      WeaTools.ls.set('theme-themeInfo', themeInfo);
    });
  }

  @action
  onLangChange(langId, langText) {
    THEME_API.changeLang({ languageId: langId }).then(() => {
      initLSValue();
      setLSValue('login', 'langId', langId);
      setLSValue('login', 'langText', langText);
      WeaTools.ls.set('languageidweaver', langId);
      window.location.reload();
    });
  }

  addMenuIds(mobxrouteurl) {
    // 添加选中的菜单id参数，用于刷新浏览器时定位选中菜单。
    if (mobxrouteurl && mobxrouteurl.indexOf('menuIds') == -1) {
      const menuIds = this.selectedMenuIds || '';
      if (menuIds) {
        if (mobxrouteurl.indexOf('?') != -1) {
          mobxrouteurl += `&menuIds=${menuIds}`;
        } else {
          mobxrouteurl += `?menuIds=${menuIds}`;
        }
      }
    }
    return mobxrouteurl;
  }

  addMenuPathIds(mobxrouteurl, menuPathIds, topId) {
    // 添加菜单路径id参数，用于自动化测试定位菜单。
    if (mobxrouteurl && mobxrouteurl.indexOf('menuPathIds') == -1) {
      if (menuPathIds) {
        if (mobxrouteurl.indexOf('?') != -1) {
          mobxrouteurl += `&menuPathIds=${topId == '0' || topId == '536' ? `${topId},${menuPathIds}` : menuPathIds}`;
        } else {
          mobxrouteurl += `?menuPathIds=${topId == '0' || topId == '536' ? `${topId},${menuPathIds}` : menuPathIds}`;
        }
      }
    }
    return mobxrouteurl;
  }

  addHideParams(mobxrouteurl) {
    // 添加隐藏主题顶部和左侧参数
    const { hideHeader, hideAside } = this.searchParams;

    if (hideHeader) {
      if (mobxrouteurl.indexOf('?') != -1) {
        mobxrouteurl += `&hideHeader=${hideHeader}`;
      } else {
        mobxrouteurl += `?hideHeader=${hideHeader}`;
      }
    }

    if (hideAside) {
      if (mobxrouteurl.indexOf('?') != -1) {
        mobxrouteurl += `&hideAside=${hideAside}`;
      } else {
        mobxrouteurl += `?hideAside=${hideAside}`;
      }
    }

    return mobxrouteurl;
  }

  @action
  onLoadMain(obj) {
    let { url = '', mobxrouteurl = '', target = 'mainFrame', topId = '', pathIds = '' } = obj;

    if (target != 'mainFrame' && url && url != 'javascript:void(0);') {
      window.open(url, target);
    } else {
      // 当路由地址不存在时，调用工具方法，解析单页地址中的路由地址
      if (!mobxrouteurl && url) {
        const urlObj = WeaTools.checkStdRouter(url) || {};
        if (urlObj.isRouter && urlObj.url) {
          mobxrouteurl = urlObj.url;
        }
      }

      if (mobxrouteurl) {
        document.getElementById('themeLayoutFrame').style.visibility = 'hidden';
        document.getElementById('themeLayoutRoute').style.display = 'block';
        document.getElementById('mainFrame').src = 'about:blank';

        mobxrouteurl = this.addMenuIds(mobxrouteurl);
        mobxrouteurl = this.addMenuPathIds(mobxrouteurl, pathIds, topId);
        mobxrouteurl = this.addHideParams(mobxrouteurl);

        if (/^\/main/.test(mobxrouteurl)) {
          weaHistory.push({ pathname: mobxrouteurl });
        } else {
          weaHistory.push({ pathname: `/main${mobxrouteurl}` });
        }
      } else if (url && url != 'javascript:void(0);') {
        mobxrouteurl = '/main';
        mobxrouteurl = this.addMenuIds(mobxrouteurl);
        mobxrouteurl = this.addMenuPathIds(mobxrouteurl, pathIds, topId);
        mobxrouteurl = this.addHideParams(mobxrouteurl);

        weaHistory.push({ pathname: mobxrouteurl });

        url = url.replace(/(jsp#)|(html#)/g, (item) => item.replace(/(jsp)|(html)/g, (type) => `${type}?__random__=${Date.now()}`));

        document.getElementById('mainFrame').src = url;
        document.getElementById('themeLayoutFrame').style.visibility = 'visible';
        document.getElementById('themeLayoutRoute').style.display = 'none';
      }
    }

    // 多语言监测
    const languageidweaver = WeaTools.ls.getStr('languageidweaver');
    const multiLangs = this.multiLangs;
    if (languageidweaver && multiLangs && multiLangs.length > 1) {
      WeaTools.checkLang && WeaTools.checkLang();
    }
  }

  @action
  onLogout() {
    Modal.confirm({
      title: getLabel(15172, '系统提示'),
      content: getLabel(16628, '确定要退出系统吗？'),
      onOk: () => {
        // 执行退出前事件
        doEvent('beforLogout', () => {
          LOGIN_API.logout().then((result) => {
            // 退出时修改清除缓存标识
            WeaTools.ls.set('isInitLSValue', false);
            WeaTools.ls.set('ennableTrans', 0);

            // 执行退出成功后事件
            doEvent('afterLogout', () => {
              // 退出成功回调
              if (window.onLogoutCallback && typeof window.onLogoutCallback == 'function') {
                window.onLogoutCallback();
              }
              WeaTools.ssoLogout(result, false);
            });
          });
        });
      },
    });
  }
}
